<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product_upload extends OC_Controller
{
    protected $path_img_upload_folder;
    protected $path_img_thumb_upload_folder;
    protected $path_url_img_upload_folder;
    protected $path_url_img_thumb_upload_folder;
    protected $delete_img_url;

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->model('products/product_model', 'pdm');

        $this->setPath_img_upload_folder(OC_FRONT_DIR."ocimages/products/");
        $this->setPath_img_thumb_upload_folder(OC_FRONT_DIR."ocimages/products/thumbnail/");
        $this->setDelete_img_url('');
        $this->setPath_url_img_upload_folder("products/product_upload/appimage/products/");
        $this->setPath_url_img_thumb_upload_folder("products/product_upload/appimage/products/thumbnail/");
    }

    function _remap($method, $params = array())
    {
        parent::_remap($method, $params);
        
        if (method_exists($this, $method))
            return call_user_func_array(array($this, $method), $params);
        else
            show_404();
    }

    public function index()
    {
        $this->load->view('products/upload_view');
    }

    public function upload_img($p_id)
    {
        // sleep(1);

        $name = $_FILES['userfile']['name'];
        $name = is_array($name) ? $name[0] : $name;

        $name = strtr($name, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
        $name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);

        $config['upload_path'] = $this->getPath_img_upload_folder();
        $config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
        // $config['max_size'] = '1000';

        // $config['file_name'] = $name;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if ($this->do_upload())
        {
            $data = $this->upload->data();
            $name = $data['file_name'];

            $config['new_image'] = $this->getPath_img_thumb_upload_folder();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $this->getPath_img_upload_folder() . $name;
            $config['create_thumb'] = FALSE;
            $config['maintain_ratio'] = TRUE;
            $config['width'] = 100;
            $config['height'] = 100;

            $this->load->library('image_lib', $config);

            $this->image_lib->resize();

            $info = new stdClass();

            $info->name = $name;
            $info->name = $data['orig_name'];
            $info->size = $data['file_size'];
            $info->type = $data['file_type'];

            // save to database
            $this->pdm->add_image(array(
                'pi_filename' => $data['file_name'],
                'pi_origname' => $data['orig_name'],
                'pi_p_id'     => $p_id
            ));

            $info->url = site_url($this->getPath_url_img_upload_folder() . "/". $name);
            $info->thumbnailUrl = site_url($this->getPath_url_img_thumb_upload_folder() . "/". $name);
            $info->delete_url = $this->getDelete_img_url() . $name;
            $info->delete_type = 'DELETE';

            if ($this->input->is_ajax_request())
            {   
                echo json_encode(array(
                    'files' => array($info)
                ));
            }
            else
            {   
                $file_data['upload_data'] = $this->upload->data();
                echo json_encode(array($info));
            }
        }
        else
        {
            $error = array('error' => $this->upload->display_errors('',''));
            echo json_encode(array($error));
        }

    }

    public function do_upload()
    {
        if ( ! $this->upload->do_upload())
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public function deleteImage()
    {
        //Get the name in the url
        $file = $this->uri->segment(3);

        $success = unlink($this->getPath_img_upload_folder() . $file);
        $success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);

        //info to see if it is doing what it is supposed to 
        $info = new stdClass();
        $info->sucess = $success;
        $info->path = $this->getPath_url_img_upload_folder() . $file;
        $info->file = is_file($this->getPath_img_upload_folder() . $file);
        if (IS_AJAX)
        {//I don't think it matters if this is set but good for error checking in the console/firebug
            echo json_encode(array($info));
        }
        else
        {
            //here you will need to decide what you want to show for a successful delete
            var_dump($file);
        }
    }


    //Load the files
    public function get_files()
    {
        $this->get_scan_files();
    }

    //Get info and Scan the directory
    public function get_scan_files()
    {
        $file_name = isset($_REQUEST['file']) ?
                basename(stripslashes($_REQUEST['file'])) : null;
        if ($file_name)
        {
            $info = $this->get_file_object($file_name);
        }
        else
        {
            $info = $this->get_file_objects();
        }
        header('Content-type: application/json');
        echo json_encode($info);
    }

    protected function get_file_object($file_name)
    {
        $file_path = $this->getPath_img_upload_folder() . $file_name;
        if (is_file($file_path) && $file_name[0] !== '.')
        {

            $file = new stdClass();
            $file->name = $file_name;
            $file->size = filesize($file_path);
            $file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
            $file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
            //File name in the url to delete 
            $file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
            $file->delete_type = 'DELETE';

            return $file;
        }
        return null;
    }

    //Scan
    protected function get_file_objects()
    {
        return array_values(array_filter(array_map(
            array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
        )));
    }



    // GETTER & SETTER 
    public function getPath_img_upload_folder()
    {
        return $this->path_img_upload_folder;
    }

    public function setPath_img_upload_folder($path_img_upload_folder)
    {
        $this->path_img_upload_folder = $path_img_upload_folder;
    }

    public function getPath_img_thumb_upload_folder()
    {
        return $this->path_img_thumb_upload_folder;
    }

    public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder)
    {
        $this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
    }

    public function getPath_url_img_upload_folder()
    {
        return $this->path_url_img_upload_folder;
    }

    public function setPath_url_img_upload_folder($path_url_img_upload_folder)
    {
        $this->path_url_img_upload_folder = $path_url_img_upload_folder;
    }

    public function getPath_url_img_thumb_upload_folder()
    {
        return $this->path_url_img_thumb_upload_folder;
    }

    public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder)
    {
        $this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
    }

    public function getDelete_img_url()
    {
        return $this->delete_img_url;
    }

    public function setDelete_img_url($delete_img_url)
    {
        $this->delete_img_url = $delete_img_url;
    }
}